angular.module('BaseControl')

.directive("btnfind", ['$compile','BaseConst', 'BaseEnum', 'BaseModule', 'BaseFunction', 'BaseClass',
    function($compile, BaseConst, BaseEnum, BaseModule, BaseFunction, BaseClass) {
    return {
        restrict: "E",	// 指令是一个元素 (并非属性)，备选项有"A"、"E" 和 "C"， "M" ,分别代表attribute、element、class和comment（默认值为"A"）
        scope: {
            module : '=?',
            change: '&'
        },
        templateUrl: 		// 替换HTML (使用scope中的变量)
            'modules/Base/client/views/BtnFind.html',
        replace: true,			// 使用模板替换原始标记
        transclude: true,		// 不复制原始HTML内容
        controller: ['$scope', function($scope) {
            $scope.GirdModule;
            $scope.Columns = new Array();
            $scope.ID = BaseFunction.getGuid();

            var isCreateDataGrid = false;
            var createDataGrid = function(){
                if (!isCreateDataGrid) {
                    var dataGridHtml = '<DataGrid module="GirdModule" rowdblclick="rowDblClick()" isedit="false" height="430px">';
                    for (var i = 0; i < $scope.Columns.length; i++) {
                        if($scope.Columns[i].Type == BaseEnum.ControlType.TextBox){
                            dataGridHtml += '<Column Type="TextBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '"></Column>';
                        }
                        else if($scope.Columns[i].Type == BaseEnum.ControlType.CheckBox){
                            dataGridHtml += '<Column Type="CheckBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '"></Column>';
                        }
                        else if($scope.Columns[i].Type == BaseEnum.ControlType.NumberBox){
                            if($scope.Columns[i].Round != null){
                                dataGridHtml += '<Column Type="NumberBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '" round=\'' + JSON.stringify($scope.Columns[i].Round) + '\'></Column>';
                            }
                            else{
                                dataGridHtml += '<Column Type="NumberBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '"></Column>';
                            }
                        }
                        else if($scope.Columns[i].Type == BaseEnum.ControlType.PercentBox){
                            if($scope.Columns[i].Round != null){
                                dataGridHtml += '<Column Type="PercentBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '" round=\'' + JSON.stringify($scope.Columns[i].Round) + '\></Column>';
                            }
                            else{
                                dataGridHtml += '<Column Type="PercentBox" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '"></Column>';
                            }
                        }
                        else if($scope.Columns[i].Type == BaseEnum.ControlType.DropDownList){
                            $scope.Columns[i].Enum = eval("$scope.$parent." + $scope.Columns[i].Enum);
                            dataGridHtml += '<Column Type="DropDownList" displayname="' + $scope.Columns[i].DisplayName + '" enum="Columns[' + i.toString() + '].Enum" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '"></Column>';
                        }
                        else if($scope.Columns[i].Type == BaseEnum.ControlType.Calendar){
                            if($scope.Columns[i].CalendarType == BaseEnum.DateTimeFormat.DateTime){
                                dataGridHtml += '<Column Type="Calendar" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '" format="datetime"></Column>';
                            }
                            else{
                                dataGridHtml += '<Column Type="Calendar" displayname="' + $scope.Columns[i].DisplayName + '" width="' + $scope.Columns[i].Width + '" valuefield="' + $scope.Columns[i].ValueField + '" format="date"></Column>';
                            }
                        }
                    }
                    dataGridHtml += '</DataGrid>';

                    $compile(dataGridHtml)($scope, function (clone, $scope) {
                        $scope._DataGridElement.appendChild(clone[0]);
                    });
                    isCreateDataGrid = true;
                }
                else{
                    $scope.GirdModule.emitReloadEvent();
                }
            };
            $scope.btnClick = function() {
                if($scope.module.EntityName == undefined || $scope.module.EntityName == null || $scope.module.EntityName.trim() == ''){
                    event.stopPropagation();
                    return;
                }
                createDataGrid();
            };
            $scope.btnOKClick = function(){
                if($scope.GirdModule.FocusedRecord == null){
                    BaseFunction.alert('请选择记录！');
                    event.stopPropagation();
                    return;
                }

                if($scope.module.FocusedRecord == null || $scope.module.FocusedRecord._id != $scope.GirdModule.FocusedRecord._id){
                    $scope.module.FocusedRecord = $scope.GirdModule.FocusedRecord;
                    if($scope.module.AfterOnLoad != null){
                        $scope.module.AfterOnLoad([$scope.GirdModule.FocusedRecord]);
                    }
                    $scope.change();
                }

                $('#' + $scope.ID).modal('hide');
            };
            $scope.rowDblClick = function(){
                // if($scope.module.FocusedRecord == null || $scope.module.FocusedRecord._id != $scope.GirdModule.FocusedRecord._id){
                //     $scope.module.FocusedRecord = $scope.GirdModule.FocusedRecord;
                //     $scope.$parent.$digest();
                //     $scope.change();
                // }
                // $('#' + $scope.ID).modal('hide');
                $scope._BtnOKElement.click();
            };
        }],
        link: function (scope, element, attrs) {
            scope.Enabled = true;
            scope.Visible = true;
            scope.WindowTitle = '参照';
            scope.Condition = scope.module.Condition;
            scope.OrderBy = scope.module.OrderBy;
            scope.Populate = scope.module.Populate;

            scope._DataGridElement = element[0].children[1].children[0].children[0].children[1]; //angular.element(element[0].children[1].children[0].children[0].children[1]);
            scope._BtnOKElement = element[0].children[1].children[0].children[0].children[2].children[1];
            if (attrs["windowtitle"] != undefined && attrs["windowtitle"].trim() != "") {
                scope.WindowTitle = attrs["windowtitle"].trim();
            }
            if (attrs["condition"] != undefined && attrs["condition"].trim() != "") {
                scope.Condition = eval("(" + attrs["condition"].trim() + ")");
            }
            if (attrs["orderby"] != undefined && attrs["orderby"].trim() != "") {
                scope.OrderBy = eval("(" + attrs["orderby"].trim() + ")");
            }
            if (attrs["populate"] != undefined && attrs["populate"].trim() != "") {
                if(attrs["populate"].trim().substring(0, 1) == "{"){
                    scope.Populate = eval("(" + attrs["populate"].trim() + ")");
                }
                else{
                     scope.Populate = attrs["populate"].trim();
                }
            }

            scope.GirdModule = BaseModule.initModule(scope, scope.module.EntityName);
            scope.GirdModule.Condition = scope.Condition;
            scope.GirdModule.OrderBy = scope.OrderBy;
            scope.GirdModule.Populate = scope.Populate;
            scope.GirdModule.PageSize = 13;
            scope.GirdModule.LoadMode = BaseEnum.LoadMode.CacheAndPaging;

            for(var i=0; i<scope._DataGridElement.children.length; i++){
                var column = {
                    Type: BaseEnum.ControlType.TextBox,
                    DisplayName: 'XXX',
                    Width: '100px',
                    ValueField: '_id',
                    Round: null,         //数值和百分比控件可以使用
                    Enum: null,
                    CalendarType: BaseEnum.DateTimeFormat.DateTime    //日历控件可以使用
                };

                var columnDom = scope._DataGridElement.children[i];
                if (columnDom.getAttribute("type") != undefined && columnDom.getAttribute("type").trim() != "") {
                    var type = columnDom.getAttribute("type").trim().toLowerCase();

                    if(type == 'textbox' || type == '0'){
                        column.Type = BaseEnum.ControlType.TextBox;
                    }
                    else if(type == 'checkbox' || type == '1'){
                        column.Type = BaseEnum.ControlType.CheckBox;
                    }
                    else if(type == 'numberbox' || type == '2'){
                        column.Type = BaseEnum.ControlType.NumberBox;
                    }
                    else if(type == 'percentbox' || type == '3'){
                        column.Type = BaseEnum.ControlType.PercentBox;
                    }
                    else if(type == 'dropdownlist' || type == '5'){
                        column.Type = BaseEnum.ControlType.DropDownList;
                        column.Enum = columnDom.getAttribute("enum").trim();
                    }
                    else if(type == 'calendar' || type == '6'){
                        column.Type = BaseEnum.ControlType.Calendar;
                    }
                }
                if (columnDom.getAttribute("displayname") != undefined && columnDom.getAttribute("displayname").trim() != "") {
                    column.DisplayName = columnDom.getAttribute("displayname").trim();
                }
                if (columnDom.getAttribute("width") != undefined && columnDom.getAttribute("width").trim() != "") {
                    column.Width = columnDom.getAttribute("width").trim();
                }
                if (columnDom.getAttribute("valuefield") != undefined && columnDom.getAttribute("valuefield").trim() != "") {
                    column.ValueField = columnDom.getAttribute("valuefield").trim();
                }
                if (columnDom.getAttribute("round") != undefined && columnDom.getAttribute("round").trim() != "") {
                    var round = eval("(" + columnDom.getAttribute("round").trim() + ")");

                    var precision = 2;
                    var roundType = BaseEnum.RoundType.AccondValueRound.Value;
                    var roundValue = 5;

                    if(round.Precision != undefined){
                        precision = round.Precision;
                    }
                    if(round.RoundType != undefined){
                        roundType = round.RoundType;
                    }
                    if(round.RoundValue != undefined){
                        roundValue = round.RoundValue;
                    }

                    column.Round = new BaseClass.Round(precision, roundType, roundValue);
                }
                if (columnDom.getAttribute("calendartype") != undefined && columnDom.getAttribute("calendartype").trim().toLocaleLowerCase() == "date") {
                    column.CalendarType = BaseEnum.DateTimeFormat.Date;
                }
                scope.Columns.push(column);
            }

            scope.$watch(
                function(){
                    return attrs["enabled"];
                },
                function(){
                    if (attrs["enabled"] != undefined && attrs["enabled"].trim().toLocaleLowerCase() == "false") {
                        scope.Enabled = false;
                    }
                    else{
                        scope.Enabled = true;
                    }
                }
            );

            scope.$watch(
                function(){
                    return attrs["visible"]
                },
                function(){
                    if (attrs["visible"] != undefined && attrs["visible"].trim().toLocaleLowerCase() == "false") {
                        scope.Visible = false;
                    }
                    else{
                        scope.Visible = true;
                    }
                }
            );
        }
    }
}]);